$(function(){
	//页面加上查询条件
	showCondition(true);

	
	paramTabPage[tabId].type1 = "";
	paramTabPage[tabId].groupName = $('#'+tabId+' #userName').val();
	//获取主诊组 所在的科室代码
	$.ajax({
		url :contextPath +"/doctorMonitor/getUserDepCode.dhc",
		async : false,
		type : "POST",
		success : function(result) {
			paramTabPage[tabId].depCode = result;
		}
	});
	
	
	// 根据当前的科室组code获取科室组名以及调用common方法

	getQuotas("clinicMonitor_1", loadData_1, "clinic-ul");

	function loadData_1(totalQuota){
		//科室 (1.dep 2.All) 
		loadDoctorAllQuota("clinic",totalQuota,"clinicQuotasTopId","clinic-ul");	
	}
	//加载病例
	loadCase();
	
});

////////////////////////////////////////
function getQuotaData(nodes){
	var quotas = [];
	for(var o in nodes){
		var node = nodes[o];
		var quota = node;
		if(node.checked){
			quotas.push(quota);
			if(node.children || node.isParent){
				getCheckedNodes(node.children, quota);
			}
		}
	}
	function getCheckedNodes(nodes, quotas){
		quotas.children = [];
		for(var o in nodes){
			var node = nodes[o];
			var quota = node;
			if(node.checked){
				quotas.children.push(quota);
				if(node.children || node.isParent){
					getCheckedNodes(node.children, quota);
				}
			}
		}
	}
	return quotas;
}
////////////////////////////////////////////////////
//封装页面初始化开始加载指标的方法
function getQuotas(pageCode, loadData, container){
	$.post(contextPath + "/quota/getQuotas.dhc", {pageCode: pageCode}).done(function(data){
		if(data.data.length==0){
			drgUI.error("没有配置指标,请联系管理员") ;
		}
		totalQuota = arrayToTree(data.data, "id", "pid");
		var zTrees = $.extend(true, [], totalQuota);
		totalQuota = getQuotaData(totalQuota);
		loadData(totalQuota);
		loadQuotaSettings(pageCode, loadData, zTrees, container);
	});
}
///////////////////////////////////////////////////
//加载指标配置页面
function loadQuotaSettings(pageCode, loadData, zTrees, container){
	var quotaSettingBtn = $('<div class="ti" style="float:right; cursor:pointer;">指标配置</div>');
	$("#"+tabId+" #"+container).before(quotaSettingBtn);
	quotaSettingBtn.bind("click", function(){
		$.post(contextPath+"/pages/common/quota-tree.jsp").done(function(data){
			var dialog  = $(data);
			dialog.find(".modal-title").html("指标配置选项");
			var str = '';
			str += '<div class="zTreeDemoBackground">';
			str += '<ul id="treeDemo" class="ztree"></ul>';
			str += '</div>"';
			dialog.find(".echartscq").html(str);
			
			var setting = {
					view: {
						selectedMulti: false
					},
					check: {
						enable: true
					},
				};
			$.fn.zTree.init(dialog.find("#treeDemo"), setting, zTrees);
			dialog.find('#save').on('click', function(){
				dialog.find('#save').attr("disabled", "");
				var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				zTrees = zTree.getNodes();
				var nodes =  $.extend(true, [], zTrees);
				totalQuota = getQuotaData(nodes);
				var zTreeSimp = zTree.transformToArray(zTrees);
				var ajaxCount = zTreeSimp.length;
				var ajaxS = 0;
				var errorLog;
				for(var o in zTreeSimp){
					var node = zTreeSimp[o];
					node.pageCode = pageCode;
					$.post(contextPath + "/quota/saveQuotas.dhc", {param: JSON.stringify(node)}).done(function(data){
						ajaxS ++;
						if(!data.success){
							errorLog += "指标("+node.code+")报错\n"+data.errorMessage;
							errorLog += "\n";
						}
					})
				}
				var timer = setInterval(function(){
					if(ajaxS == ajaxCount){
						clearInterval(timer);
						if(errorLog){
							dialog.modal('hide');
							drgUI.error(errorLog) ;
						}else{
							dialog.trigger('complete');
						}
						
					}
				}, 500);
			}).end().modal({
				keyboard : false
			}).on({
				'hidden.bs.modal' : function() {
					dialog.remove();
				},
				'complete' : function() {
					dialog.modal('hide');
					
					loadData(totalQuota);
	            }
			});
		})
	});
}

/*
 * 加载页面全院部分页面数据
 */
////////////////////////////////////////////////
function loadDoctorAllQuota(monitorType, totalQuota, divId,commonul) {
	var str = '';
	var ul = '';
	for (var o in totalQuota) {
		var quotaTypes = totalQuota[o].children;
		if (totalQuota.length > 0) {
			// 拼接ul
			if (o == 0) {
				ul += '<li role="presentation" class="active">';
			} else {
				ul += '<li role="presentation">';
			}
			ul += '<a href="#' + totalQuota[o].code + 'QuaId-hosp' + tabId
					+ '" role="tab" data-toggle="tab" class="top-tab">'
					+ totalQuota[o].name + '</a>';
			ul += '</li>';
	       $("#" + tabId +" #"+commonul).html(ul);
			// 开始拼接div
			if (o == 0) {
				str += '<div role="tabpanel" class="tab-pane active" id="'
						+ totalQuota[o].code + 'QuaId-hosp' + tabId + '">';
			} else {
				str += '<div role="tabpanel" class="tab-pane" id="'
						+ totalQuota[o].code + 'QuaId-hosp' + tabId + '">';
			}
			str += '<div class="paddingd10">';
			str += '<div class="row" >';
		}
		for (var o in quotaTypes) {
			var quotas = quotaTypes[o];
			str += ' <div class="col-xs-4"> ';
			str += '     <div class="infocq"> ';
			str += '         <div class="tii margind10"><span>'
					+ quotas.name + '</span></div> ';
			str += '         <div class="ci"> ';
			for (var o1 in quotas.children) {
				var quota = quotas.children[o1];
				var quotaCode = quota.code;
				var quotaName = quota.name;
				var quotaType = quota.type;
				str += '             <div class="row contotalcq2"> ';
				str += '                <div class="col-xs-6">'+ quotaName + '</div> ';
				if("ratio"==quotaType){
					str += '                 <div class="col-xs-6" id="'+quotaCode+'-value">'+getQuotaValue(quotaCode, monitorType, function(value, valuecc, code){
						$("#" + tabId + " #" + divId + " #"+code+"-value").html(comparePercent(value, valuecc));
					})+'</div> ';
				}else{
					str += '                 <div class="col-xs-6" id="'+quotaCode+'-value">'+getQuotaValue(quotaCode, monitorType, function(value, valuecc, code){
						$("#" + tabId + " #" + divId + " #"+code+"-value").html(compareValue(value, valuecc));
					})+'</div> ';
				}
				str += '             </div> ';
			}
			str += '         </div> ';
			str += '     </div> ';
			str += ' </div> ';
		}
		if (totalQuota.length > 0) {
			str += '</div>';
			str += '</div>';
			str += '</div>';
		}
	}
	$("#" + tabId + " #" + divId).html(str);
}
///////////////////////////////////////
function getQuotaValue(quotaCode, monitorType, callback){
	$.post(contextPath + "/Monitor/monitor.dhc", {
		'dateFrom' : paramTabPage[tabId].dateFrom,
		'dateTo' : paramTabPage[tabId].dateTo,
		'mrLot' : paramTabPage[tabId].mrLot,
		'mrType' : paramTabPage[tabId].mrType,
		'compareType' : paramTabPage[tabId].compareType,
		'pType' : paramTabPage[tabId].pType,
		'monitorType' : monitorType,
		'quotaCode' : quotaCode,
		'pardepCode' : paramTabPage[tabId].depCode,
		'pardepgroupCode' : paramTabPage[tabId].depGroupCode,
		'pargroupName' : paramTabPage[tabId].groupName,
		'parwardCode' : paramTabPage[tabId].wardCode,
		'parmdcCode' : paramTabPage[tabId].mdcCode,
		'paradrgCode' : paramTabPage[tabId].adrgCode,
		'pardrgCode' : paramTabPage[tabId].drgCode
	}).done(function(data) {
		if(data.success){
			if(data.data.length>0){
				data = data.data[0];
				callback(data.QuotaValue, data.QuotaValuecc, quotaCode);
			}else{
				callback("", "", quotaCode);
			}
		}else{
			callback("", "", quotaCode);
		}
	});
	return "";
}

function loadCase() {
	var tb_id='tb'+new Date().getTime();
	$('#'+tabId+' #caseListId').html('<table class="stripe cc table" style="width:100%;"  id="'+tb_id+'"'
		 		   +'style="text-align: center;">'     //transition:all .2s;
		 		  +'<thead><tr>'
		 		 +'<td style="width:80px">病案号</td>'
		 		+'<td width="80px">姓名</td>'
		 		+'<td width="40px">性别</td>'
		 		+'<td width="40px">年龄</td>'
		 		+'<td width="100px">入院时间</td>'
		 		+'<td width="100px">出院时间</td>'
		 		+'<td width="100px">出院科室</td>'
		 		+'<td width="40px">住院日</td>'
		 		+'<td width="80px">总费用</td>'
		 		+'<td width="80px">药品费用</td>'
		 		+'<td width="200px">主诊断</td>'
		 		+'<td width="80px">DRG代码</td>'
		 		+'<td width="200px">DRG描述</td>'
		 		+'<td width="200px">病组权重</td>'
		 		+'<td width="200px">平均住院日(绩效值)</td>'
		 		+'<td width="200px">次均费用(绩效值)</td>'
		 		+'</tr></thead><tbody id="table"></tbody></table>');
	loadPageData(tabId,tb_id, paramTabPage[tabId].quotaCode);
}
/**
 * 获取病例数据
 */
function loadPageData(tabId,tb_id,quotaCode){
	var columns=[ 
					{ "data": "mrNo",
						"render": function(obj, type, full){
							var mrNo = full.mrNo;
						return "<a href=\"javascript:medicalRecord('"+full.id+"','"+full.patientName+"')\">"+mrNo+"</a>";
					}},
					 { "data": "patientName" },
					 { "data": "sex",
						 "render": function(obj, type, full) {
					               var sex=full.sex;
					               if(sex == "1"){
					              	 sex = "男";
					               }else if(sex == "2"){
					              	 sex = "女";
					               }else{
					              	 sex = "未知";
					               }
					               return sex;
					           }
					 },
					 { "data": "ageYear" ,
					   "render": function(obj, type, full) {
						   if(full.ageYear>0){
							   return full.ageYear;
						   } else if(full.ageMonth>0){
							   return full.ageMonth + '月';
						   } else if(full.ageDays>0){
							   return full.ageDays + '天';
						   } else if(full.newbornDays>0){
							   return full.newbornDays + '天';
						   }
			           }
					 },
					 { "data": "inDate"},
					 { "data": "outDate",
						 "render": function(obj, type, full) {
					               return full.outDate;
					           }
					  },
					 { "data": "outDep" },
					 { "data": "inDays" },
					 { "data": "costamount", 
						 "render": function(obj, type, full) {
							 if(full.benchmark>0 && full.costamount>1*full.benchmark)//超过标杆值
				               return "<font color='red'>"+full.costamount+"</font>";
							 else
								return full.costamount;
				           }
					 },
					 { "data": "drugcost" },
					 { "data": "diagnoseDessmain" },
					 { "data": "drgcode" },
					 { "data": "drg" },
					 { "data": "weight" },
					 { "data": "avgDaysStd" },
					 { "data": "avgFeeStd" }
					];
	var ajaxFunction=function (aoData, fnCallback,oSetting ) {
    	//正在加载
   	 
   	 var iDisplayStart=aoData.start;
 	 var iDisplayLength=aoData.length;
 	 var sEcho = 1;
   	 $.ajax( {
        "dataType": 'json', 
        "type": "POST", 
        "url": contextPath + "/DrgsIndexCal/findCaseList.dhc", 
        "data": {
   		 'dateFrom':paramTabPage[tabId].dateFrom,
   		 'dateTo':paramTabPage[tabId].dateTo,
   		 'pType': paramTabPage[tabId].pType,
   		 'quotaCode': quotaCode,
   		 'pardepCode':paramTabPage[tabId].depCode,
   		 'pardepgroupCode':paramTabPage[tabId].depGroupCode,
   		 'pargroupName': paramTabPage[tabId].groupName,
   		 'parwardCode': paramTabPage[tabId].wardCode,
   		 'parmdcCode':paramTabPage[tabId].mdcCode,
   		 'paradrgCode': paramTabPage[tabId].adrgCode,
   		 'pardrgCode': paramTabPage[tabId].drgCode,
		 'page': iDisplayStart,//页面开始行数
		 'pageSize':iDisplayLength,
		 'sEcho':sEcho,
        },
        "success": function(resp) {
        	var data=[];
	       	 data.draw=aoData.draw;
	       	 data.recordsTotal=resp.data.data.iTotalRecords;
	       	 data.recordsFiltered=resp.data.data.iTotalDisplayRecords;
	       	 data.data=resp.data.data.aaData;
			 fnCallback(data,oSetting);
	
			}
      } );
    }
	var tableTitle=$('#'+tabId+' #'+tb_id).parent().parent().parent().find(".contaotalsccq").text()
	var paramsDataTables={ajaxFunction:ajaxFunction,ordering:false,autoWidth:false,tableTitle:tableTitle};
    $('#'+tabId+' #'+tb_id).dataTableServerPaging(colunms,paramsDataTables);
	if(type2){
		$("#"+tabId+" #"+tb_id+"_filter").html("<label>搜索 <input type='text' id='"+tb_id+"_filter_value' title='病人信息、出院科室、主诊断、DRG代码' placeholder='病人、出院科室、主诊断、DRG'  value='"+type2+"'></label>")
	}else{
		$("#"+tabId+" #"+tb_id+"_filter").html("<label>搜索 <input type='text' id='"+tb_id+"_filter_value' title='病人信息、出院科室、主诊断、DRG代码' placeholder='病人、出院科室、主诊断、DRG'></label>")
	}
	//重写过滤方法
	$("#"+tabId+" #"+tb_id+"_filter_value").keydown(function(e){
		if(e.keyCode==13){
			var type2 = $("#"+tabId+" #"+tb_id+"_filter_value").val();
			loadPageData(tabId,tb_id,type1,type2);
		}
	});
}











